package com.project.controller;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Map;

@Controller
@RequestMapping("/oauth")
public class OAuthController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private IUserInfoService userInfoService;

    @GetMapping("/process")
    public Object process(String code){
        String tokenUrl = "https://gitee.com/oauth/token?" +
                            "grant_type=authorization_code" +
                            "&code="+ code +
                            "&client_id=a45d31956c17aff7d5b78db137d2a9096df0cee25e8cdb7112cdc4817a393920" +
                            "&redirect_uri=http://localhost:8081/api/oauth/process" +
                            "&client_secret=8896f2db932c9e288698dfdbead6bcada0bab2445f5a7c077511f0ae64d52af0";
        String resourceUrl = "https://gitee.com/api/v5/user?access_token=";
        // 申请令牌
        Map<String,String> tokenMap = restTemplate.postForObject(tokenUrl, WebUtil.httpEntity(), Map.class);
        if(tokenMap.get("access_token") == null){
            return null;
        }
        // 根据令牌获取第三方应用资源
        Map<String,String> resourceMap = restTemplate.getForObject(resourceUrl + tokenMap.get("access_token"),Map.class);
        // 判断系统中是否已有该账号
        UserInfoBean userInfoBean = userInfoService.selectByUserName(resourceMap.get("name"));
        if(userInfoBean == null){
            // 创建一个账号保存到数据中
            userInfoBean = new UserInfoBean();
            userInfoBean.setUserName(resourceMap.get("name"));
            userInfoBean.setUserPass(DigestUtils.sha256Hex(tokenMap.get("access_token")));
            userInfoService.save(userInfoBean);
        }

        String token = JWTUtil.createToken(userInfoBean.getUserName(),userInfoBean.getUserPass(), Calendar.MINUTE,30);
        return "redirect:http://localhost:8081/manage?token="+token;
    }


}
